<!-- 公告标题 -->
<template>
    <div class="app-container">
        <el-button type="primary" @click="addNotice" v-show="this.$route.query.status != 7">
            新建
        </el-button>
        <div style="margin-bottom: 10px;"></div>
        <el-table v-loading="loading" :data="tableData" stripe style="width: 100%">
            <el-table-column type="index" label="序号" width="50" align="center">
            </el-table-column>
            <el-table-column prop="title" label="公告标题" align="center">
            </el-table-column>
            <el-table-column prop="project" label="关联项目" align="center">
            </el-table-column>
            <el-table-column prop="status" label="审批状态" align="center">
                <template slot-scope="scope">
                    <el-tag :type="statusTypeFormatter(scope.row.status)">{{ statusFormatter(scope.row.status)
                        }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="address" label="操作" align="center">
                <template slot-scope="scope">
                    <el-button @click="editNoticeRow(scope.row)" v-if="scope.row.status == 1 || scope.row.status == 4"
                        type="text" size="small">
                        编辑
                    </el-button>
                    <el-button @click="deleteNoticeRow(scope.row)" v-if="scope.row.status == 1 || scope.row.status == 4"
                        type="text" size="small">
                        移除
                    </el-button>
                    <el-button @click="checkNoticeRow(scope.row)"
                        v-if="scope.row.status == 5 || scope.row.status == 2 || scope.row.status == 3" type="text"
                        size="small">
                        查看
                    </el-button>
                    <el-button @click="releaseNoticeRow(scope.row)" v-if="scope.row.status == 3" type="text"
                        size="small">
                        发布
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-dialog :title="title" :visible.sync="noticeOpen" width="70%">
            <el-row :gutter="15">
                <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="100px">
                    <el-col :span="24">
                        <el-form-item label="公告标题" prop="title">
                            <el-input :disabled="formData.uId != null && formData.status == 2" v-model="formData.title"
                                placeholder="请输入标题" show-word-limit clearable prefix-icon='el-icon-mobile'
                                :style="{ width: '100%' }"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="关联项目" prop="project">
                            <el-input v-model="formData.project" disabled clearable :style="{ width: '100%' }">
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="项目资金" prop="money">
                            <el-input v-model="formData.money" placeholder="根据关联项目自动生成" disabled clearable
                                :style="{ width: '100%' }">
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="获取时间" prop="getTime" v-show="formData.nType == 1">
                            <el-date-picker :disabled="formData.uId != null && formData.status == 2"
                                type="datetimerange" v-model="formData.getTime" format="yyyy-MM-dd HH:mm:ss"
                                value-format="yyyy-MM-dd HH:mm:ss" :style="{ width: '100%' }" start-placeholder="开始日期"
                                end-placeholder="结束日期" range-separator="至" clearable></el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="答疑时间" prop="acceptTime" v-show="formData.nType == 1">
                            <el-date-picker :disabled="formData.uId != null && formData.status == 2"
                                type="datetimerange" v-model="formData.acceptTime" format="yyyy-MM-dd HH:mm:ss"
                                value-format="yyyy-MM-dd HH:mm:ss" :style="{ width: '100%' }" start-placeholder="开始日期"
                                end-placeholder="结束日期" range-separator="至" clearable></el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="开标时间" prop="kaiTime" v-show="formData.nType == 1">
                            <el-date-picker :disabled="formData.uId != null && formData.status == 2"
                                type="datetimerange" v-model="formData.kaiTime" format="yyyy-MM-dd HH:mm:ss"
                                value-format="yyyy-MM-dd HH:mm:ss" :style="{ width: '100%' }" start-placeholder="开始时间"
                                end-placeholder="结束时间" range-separator="至" clearable></el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="公告类型" prop="nType">
                            <el-select v-model="formData.nType" placeholder="请选择" :style="{ width: '100%' }">
                                <el-option v-for="item in dict.type.notice_type" :key="item.value" :label="item.label"
                                    :value="item.value" :disabled="projectState-1!=item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="文件上传" v-if="formData.status !== 5 && formData.status !== 1">
                            <el-upload ref="field109" action="#" :http-request="uploadDeviceFile" :file-list="fileList"
                                :before-upload="fileBeforeUpload" :on-remove="handleRemoveFile">
                                <el-button size="small" type="primary" icon="el-icon-upload">点击上传</el-button>
                            </el-upload>
                        </el-form-item>
                        <template v-if="formData.status === 5 || formData.status === 1">
                            <el-form-item label="文件下载">
                                <el-dropdown>
                                    <el-button type="primary">
                                        下载文件 <i class="el-icon-arrow-down el-icon--right"></i>
                                    </el-button>
                                    <el-dropdown-menu slot="dropdown">
                                        <el-dropdown-item v-for="(item, index) in fileList" :key="index">
                                            <el-button type="text" @click="downloadMethod(item)"
                                                icon="el-icon-download">
                                                下载 {{ item.name }}
                                            </el-button>
                                        </el-dropdown-item>
                                    </el-dropdown-menu>
                                </el-dropdown>
                            </el-form-item>
                        </template>
                    </el-col>

                    <el-col :span="24">
                                                    <!-- <el-input v-model="formData.remark" type="textarea" placeholder="请输入多行文本"
                                :autosize="{ minRows: 4, maxRows: 4 }" :style="{ width: '100%' }"></el-input> -->
                        <el-form-item label="内容" prop="field110">
                            <editor v-model="formData.remark" :min-height="192" />
                        </el-form-item>
                    </el-col>
                </el-form>
            </el-row>
            <div slot="footer">
                <el-button v-show="formData.uId != null && formData.status == 2" type="success"
                    @click="examineNoticeRow">通过</el-button>
                <el-button v-show="formData.uId != null && formData.status == 2" type="warning"
                    @click="rejectNotice">驳回</el-button>
                <el-button v-show="formData.uId == null" type="primary" @click="handleConfirm">确定</el-button>
                <el-button v-show="formData.uId != null && formData.status < 2" type="primary"
                    @click="handleChange">修改</el-button>
                <el-button v-show="formData.uId != null && (formData.status < 2 || formData.status == 4)" type="primary"
                    @click="handleSubmit">提交</el-button>
                <el-button @click="close">取消</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
import {
    getNoiceList, getTenderProjectInfo, addTenderNotice, getNoticeInfoByUId,
    uplodaBudgetFile, submitTenderNotice, editTenderNotice, examineNoticeRow, releaseNoticeRow, deleteNoticeRow,
    rejectNotice
} from '@/api/system/purchase'
export default {
    dicts: ["notice_type"],
    data() {
        return {
            tableData: [],
            noticeOpen: false,
            formData: {
                iNumber: '',
            },
            projectState: 0,//用于判断哪些类型的选项被警用
            loading: true,
            title: '新增项目公告',
            noticeForm: {},
            noticeRule: {},
            fileList: [],
            rules: {
                title: [{
                    required: true,
                    message: '请输入单行文本',
                    trigger: 'blur'
                }],
                getTime: [{
                    required: this.projectState >= 4,
                    message: '日期范围不能为空',
                    trigger: 'change'
                }],
                kaiTime: [{
                    required: this.projectState >= 4,
                    message: '日期范围不能为空',
                    trigger: 'change'
                }],
                acceptTime: [{
                    required: this.projectState >= 4,
                    message: '时间范围不能为空',
                    trigger: 'change'
                }],
                nType: [{
                    required: true,
                    message: '请选择',
                    trigger: 'change'
                }]
            },
        }
    },
    methods: {
        async downloadMethod(fileInfoL) {
            try {
                // 获取响应
                let response = await fetch(fileInfoL.url);
                // 检查响应是否成功
                if (!response.ok) {
                    throw new Error("网络响应失败");
                }
                // 内容转变成blob地址
                let blob = await response.blob();
                // 创建隐藏的可下载链接
                let objectUrl = window.URL.createObjectURL(blob);
                let a = document.createElement("a");
                a.style.display = "none";
                a.href = objectUrl;
                a.download = fileInfoL.name;

                // 触发点击
                document.body.appendChild(a);
                a.click();

                // 移除
                URL.revokeObjectURL(a.href);
                document.body.removeChild(a);
            } catch (error) {
                console.error("下载文件时出错:", error);
            }
        },
        updateStatus(uId, newStatus) {
            // 遍历 tableData 数组
            for (let i = 0; i < this.tableData.length; i++) {
                // 找到与 uId 匹配的对象
                if (this.tableData[i].uId === uId) {
                    // 更新 status 属性
                    this.$set(this.tableData[i], 'status', newStatus);
                    // 如果使用 Vue 2.x，可以使用 this.$set 来触发视图更新
                    // 如果使用 Vue 3.x，可以直接赋值，因为 Vue 3.x 已经支持直接操作数组
                    break; // 找到匹配的对象后，跳出循环
                }
            }
        },
        handleSubmit() {
            this.formData.status = 2
            submitTenderNotice(this.formData).then(res => {
                if (res.data > 0) {
                    this.noticeOpen = false;
                    this.$message({
                        message: '提交成功',
                        type: 'success'
                    });
                    this.updateStatus(this.formData.uId, 2);
                    this.formData = {};
                    this.fileList = [];
                } else {
                    this.$message({
                        message: '提交失败',
                        type: 'error'
                    });
                }
            })
        },
        //删除文件
        handleRemoveFile(file) {
            removeFile(file.name).then(res => {
                if (res.data == 1) {
                    this.$message({
                        message: '删除成功',
                        type: 'success'
                    });
                }
                const index = this.fileList.findIndex(f => f.name === file.name);
                this.fileList.splice(index, 1); // 从 fileList 中移除一个元素，从 index 位置开始
            })
        },
        uploadDeviceFile(file) {
            // 创建formdata实例
            let formData = new window.FormData();
            // 将获取的文件通过append方法加入实例中
            formData.append("file", file.file);
            //发送axios请求
            uplodaBudgetFile(formData)
                .then(res => {
                    // 拿到后端响应的文件名称反显到列表的form
                    const fileInfo = {
                        name: res.data.name,
                        url: res.data.url,
                        size: res.data.size,
                        uid: file.file.uid,
                    };
                    this.fileList.push(fileInfo); // 直接添加文件名字符串    
                })
                .catch(err => {
                    console.error('上传文件失败:', err);
                });
        },
        //关闭弹窗
        close() {
            this.noticeOpen = false;
        },
        //新增公告标题
        handleConfirm() {
            this.title = '新增项目公告';
            this.formData.fileList = this.fileList;
            this.$refs.elForm.validate((valid) => {
                if (valid) {
                    addTenderNotice(this.formData).then(res => {
                        if (res.data > 0) {
                            this.$message({
                                message: '添加成功',
                                type: 'success'
                            });
                            this.noticeList(this.formData.iNumber);
                            this.noticeOpen = false;
                            const iNumber = this.formData.iNumber;
                            this.formData = {
                                iNumber: iNumber
                            };
                            this.fileList = [];
                        } else {
                            this.$message.warn("添加失败");
                        }
                    })
                } else {
                    this.$message({
                        message: '请填写完整',
                        type: 'waring'
                    });
                }
            })

        },
        //状态数字转换 
        statusFormatter(cellValue) {
            if (cellValue == 1) {
                return '草稿';
            } else if (cellValue == 2) {
                return '审核中';
            } else if (cellValue == 3) {
                return '审核通过';
            } else if (cellValue == 4) {
                return '驳回';
            } else if (cellValue == 5) {
                return '已发布'
            }
        },
        statusTypeFormatter(cellValue) {
            if (cellValue == 1) {
                return 'info';
            } else if (cellValue == 2) {
                return;
            } else if (cellValue == 3) {
                return 'success';
            } else if (cellValue == 4) {
                return 'warning';
            } else if (cellValue == 5) {
                return 'danger'
            }
        },
        //编辑招标公告
        editNoticeRow(row) {
            this.title = '编辑项目公告';
            getNoticeInfoByUId(row.uId).then(res => {
                res.nType=res.nType+"";
                this.formData = res;
                this.fileList = res.fileList;
            })
            this.noticeOpen = true;
        },
        //审核招标公告
        examineNoticeRow() {
            this.title = '审核项目公告';
            examineNoticeRow(this.formData).then(res => {
                if (res.data > 0) {
                    this.$message({
                        message: '修改成功',
                        type: 'success'
                    });
                    this.noticeOpen = false;
                    this.updateStatus(this.formData.uId, 3)
                    const iNumber = this.formData.iNumber;
                    this.formData = {
                        iNumber: iNumber
                    };
                    this.fileList = [];
                } else {
                    this.$message({
                        message: '修改失败',
                        type: 'error'
                    });
                }
            })
        },
        //修改
        handleChange() {
            editTenderNotice(this.formData).then(res => {
                if (res.data > 0) {
                    this.$message({
                        message: '修改成功',
                        type: 'success'
                    });
                    this.noticeOpen = false;
                    const iNumber = this.formData.iNumber;
                    this.formData = {
                        iNumber: iNumber
                    };
                    this.fileList = [];
                } else {
                    this.$message({
                        message: '修改失败',
                        type: 'error'
                    });
                }
            })
        },
        deleteNoticeRow(row) {
            this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                return deleteNoticeRow(row.uId);  // 确保这里返回一个 Promise  
            }).then(res => {
                if (res.data > 0) {
                    this.$message({
                        message: '删除成功',
                        type: 'success'
                    });
                    // 直接通过 filter 重新生成 tableData，确保状态更新  
                    this.tableData = this.tableData.filter(item => item.uId !== row.uId);
                } else {
                    this.$message({
                        message: '删除失败',
                        type: 'error'
                    });
                }
            }).catch((error) => {
                // 这里的 catch 也可以捕获 deleteNoticeRow 中的任何错误                  
                if (error) {
                    this.$message({
                        type: 'error',
                        message: '删除操作失败，请稍后重试'
                    });
                } else {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                }
            });
        },
        checkNoticeRow(row) {
            this.title = '查看项目公告';
            this.formData.uId = row.uId;
            this.noticeOpen = true;
            getNoticeInfoByUId(row.uId).then(res => {
                res.nType = res.nType + ""
                this.formData = res;
                this.fileList = res.fileList;
            })
        },
        //发布公告
        releaseNoticeRow(row) {
            this.tableData.forEach(ele => {
                if (ele.nType == 1 && row.nType == 1 && ele.uId != row.uId) {
                    this.$confirm('已存在招标公共,此公共将覆盖上一个公告, 是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        this.tableData = this.tableData.filter(item => item.nType != ele.nType);
                        releaseNoticeRow(row.uId).then(res => {
                            if (res.data > 0) {
                                this.$message({
                                    message: '发布成功',
                                    type: 'success'
                                });
                                this.updateStatus(row.uId, 5)
                            } else {
                                this.$message({
                                    message: '发布失败',
                                    type: 'error'
                                });
                            }
                        })
                    }).catch(() => {
                        this.$message({
                            type: 'info',
                            message: '已取消发布'
                        });
                    });
                } else {
                    releaseNoticeRow(row.uId).then(res => {
                        if (res.data > 0) {
                            this.$message({
                                message: '发布成功',
                                type: 'success'
                            });
                            this.updateStatus(row.uId, 5)
                        } else {
                            this.$message({
                                message: '发布失败',
                                type: 'error'
                            });
                        }
                    })
                }
            })

        },
        addNotice() {
            if (!(this.$store.getters.roles.includes('admin')||this.$store.getters.roles.includes('common'))) {
                this.$message.error('你没有这个权限');
                return false;
            }
            this.noticeOpen = true;
            this.title = "新增公告"
            const iNumber = this.formData.iNumber;
            this.fileList = [];
            this.formData = {
                iNumber: iNumber,
                fileList: [],
            };

            getTenderProjectInfo(this.formData.iNumber).then(res => {
                this.formData.project = res.tenderProjectInfo.iName
                this.formData.money = res.tenderProjectInfo.pBudget
                this.noticeOpen = true;
            })
        },

        fileBeforeUpload(file) {
            let isRightSize = file.size / 1024 / 1024 < 10
            if (!isRightSize) {
                this.$message.error('文件大小超过 10MB')
            }
            return isRightSize
        },

        noticeList(iNumber) {
            getNoiceList(iNumber).then(res => {
                this.loading = false;
                this.tableData = res;
            })
        },
        //驳回
        rejectNotice(row) {
            rejectNotice(this.formData.uId).then((res) => {
                if (res.data > 0) {
                    this.$message({
                        message: '驳回成功',
                        type: 'success'
                    });
                    this.noticeOpen = false;
                    this.updateStatus(this.formData.uId, 4)
                    const iNumber = this.formData.iNumber;
                    this.formData = {
                        iNumber: iNumber
                    };
                    this.fileList = [];
                }
            }).catch(err => {
                this.$message({
                    message: '驳回失败',
                    type: 'error'
                });
            })
        }
    },
    mounted() {
        const query = this.$route.query.iNumber;
        this.noticeList(query);
        this.formData.iNumber = query;
        getTenderProjectInfo(this.formData.iNumber).then(res => {
            this.formData.project = res.tenderProjectInfo.iName
            this.formData.money = res.tenderProjectInfo.pBudget
            this.projectState = res.tenderProjectInfo.projectState

            this.$route.query.status = res.tenderProjectInfo.projectState
            if (res.notice != null) {
                this.$route.query.getEndTime = res.notice.getEndTime;
                this.$route.query.getStartTime = res.notice.getStartTime;
            }
        })
        console.log(this.$route.query, "这是测试路由中的参数");

    },
}
</script>
<style scoped></style>
